<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>SeaJS Test Suite</title>
<link rel="stylesheet" href="style.css?20121112.css"/>
</head>
<body>
<script src="config.js?20121120.js"></script>
<script>
var result

(function() {

  var container, summary, reporter, go
  var current, running, timeoutTimer
  var startTime, endTime
  var tests = this['testCases']
  var consoleMode = location.search.indexOf('console') > 0


  window.onload = function() {
    container = document.getElementById('container')
    reporter = document.getElementById('reporter')
    summary = document.getElementById('summary')

    go = document.getElementById('go')
    go.setAttribute('autocomplete', 'off')

    go.onclick = function() {
      // start
      if (current === 0) {
        start()
      }
      // pause
      else if (running) {
        pause()
      }
      // resume
      else {
        resume()
      }
    }

    // Start automatically
    start()

    document.getElementById('info').innerHTML = navigator.userAgent
  }


  function start() {
    reporter.innerHTML = ''
    startTime = new Date().getTime()

    reset()
    resume()
  }


  function pause() {
    running = false
    go.innerHTML = 'Resume'
  }


  function resume() {
    running = true
    go.innerHTML = 'Pause'
    testNext()
  }


  function reset() {
    current = 0
    result = {
      pass: { count: 0, cases: [] },
      fail: { count: 0, cases: [] },
      warn: { count: 0, cases: [] },
      error: { count: 0, cases: [] }
    }

    running = false
    go.innerHTML = 'Go'
    timeoutTimer = 0
  }


  window.testNext = function() {
    var test = tests[current++]
    clearTimeout(timeoutTimer)
    clear()

    if (test) {
      // paused
      if (running === false) {
        printResults('[PAUSED]', 'warn')
        printStepInfo()
        printErrors()
        return
      }

      var url = getUrl(test)
      printHeader(test, url)
      load(url)
      makeSureGoOn(test)

      printStepInfo()
    }
    else {
      endTime = new Date().getTime()
      printStepInfo()
      printErrors()
      printResults('[END]')
      reset()
    }
  }


  window.printResults = function(txt, style, stopped) {
    var d = document.createElement('div')
    d.innerHTML = txt
    d.className = style

    reporter.appendChild(d)
    reporter.scrollTop = reporter.scrollHeight

    if (!stopped) {
      var r = result[style]
      if (r) {
        r.count += 1
        r.cases.push(tests[current - 1])
      }
    }

    consoleMode && print2Console(txt, style)
  }


  function getUrl(test) {
    var url = ''

    if (test.indexOf('modules/') === 0) {
      url = 'sandbox.html?' + encodeURIComponent(test + '/program.js')
    }
    else if (test.indexOf('unit/') === 0) {
      url = 'sandbox.html?' + encodeURIComponent(test)
    }
    else if (test.indexOf('bootstrap/') === 0) {
      url = test + '.html'
    }
    else {
      url = test + '/test.html'
    }

    url += (url.indexOf('?') > 0 ? '&' : '?') + 't=' + new Date().getTime()
    return url
  }


  function clear() {
    var iframes = document.getElementsByTagName('iframe')
    var length = iframes.length

    for (var i = 0; i < length; i++) {
      iframes[i].parentNode.removeChild(iframes[i])
    }
  }


  function load(url) {
    var frame = document.createElement('iframe')
    container.appendChild(frame)
    frame.src = url
  }


  function printHeader(test, url) {
    var h = document.createElement('h3')
    h.innerHTML = test +
        (url ? ' <a class="hash" target="_blank" href="' + url + '">#</a>' : '')
    reporter.appendChild(h)

    consoleMode && print2Console(test)
  }


  function printStepInfo() {
    var test = tests[current - 1]

    var html = summary.innerHTML =
        (current - 1) + ' / ' + tests.length + ' { &nbsp;' +
            'Passed: <span class="pass">' + result.pass.count + '</span> ' +
            'Failed: <span class="fail">' + result.fail.count + '</span> ' +
            'Errors: <span class="error">' + result.error.count + '</span>}' +
            '&nbsp; ' +
            (test ?
                'Running ' + test + ' ... ' :
                'Elapsed Time: ' + (endTime - startTime) / 1000 + 's')

    if (!test && consoleMode) {
      printHeader('Summary')
      print2Console(html.replace(/&nbsp;/g, '').replace(/<\/?span[^>]*>/g, ''))
    }
  }


  function printErrors() {
    if (result.fail.count + result.error.count + result.warn.count === 0) return
    printHeader('Error Cases:')

    for (var type in result) {
      if (type === 'pass') continue
      var obj = result[type]

      if (obj.count) {
        var cases = obj.cases

        for (var i = 0; i < cases.length; i++) {
          var test = cases[i]
          printResults('[' + type.toUpperCase() + '] ' + test + ' ' +
              (consoleMode ?
                  getUrl(test) :
                  '<a class="hash" target="_blank" href="' + getUrl(test) + '">#</a>'),
              type, true)
        }
      }
    }

    printResults('[DONE]')
  }


  function makeSureGoOn(test) {
    // Wait 20s
    timeoutTimer = setTimeout(function() {
      printResults('[WARN] Time is out for this test case: ' + test, 'warn')
      testNext()
    }, 20000)
  }


  function print2Console(msg, type) {
    if (type !== 'warn' && type !== 'error') type = 'log'
    console[type](msg)
  }

})()
</script>

<div id="container">
  <div id="header">
    <div id="title">Test Suite for SeaJS</div>
    <div id="summary"></div>
  </div>
  <div id="reporter"></div>
  <button id="go" class="btn">Go</button>
  <p id="info"></p>
</div>

</body>
</html>
